﻿using System;
using System.Windows;
using ImageAppDataModels;
using BrainTechLLC.WebCam;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using BrainTechLLC.Communications;
using BrainTechLLC;

namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for WebCamWindow.xaml
    /// </summary>
    public partial class WebCamWindow : Window
    {
        public WebcamVideoControl WebCam;
        public P2PCommunicationsLibrary commAudio = new P2PCommunicationsLibrary();
        public P2PCommunicationsLibrary commVideo = new P2PCommunicationsLibrary();

        public WebCamWindow()
        {
            InitializeComponent();
            this.Closing += new System.ComponentModel.CancelEventHandler(WebCamWindow_Closing);
        }

        void WebCamWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (WebCam != null)
            {
                WebCam.StopProcessingImages();
                WebCam.StopRunning();
                commAudio.GracefulShutdown();
                commVideo.GracefulShutdown();
            }
        }

        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Escape)
            {
                e.Handled = true;
                this.Close();
            }
        }

        private void webCamControl_Load(object sender, EventArgs e)
        {
            commAudio.AcceptIncomingConnections(System.Net.IPAddress.Any, 4005);
            commVideo.AcceptIncomingConnections(System.Net.IPAddress.Any, 4006);
            WebCam = webCamControl;
            var results = WebcamVideoControl.GetAvailableCaptureDevices(null);
            WebCam.OpenCaptureDevice(results[0]);

            WebCam.comm = commVideo;
            WebCam.EnableRemoteConnections = true;
            Dispatcher.BeginInvoke(new VoidDelegate(() => WebCam.BeginProcessingImages(this.formsHost, true, true)));
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            WebCam.ConnectToComputer = txtAddress.Text;
            WebCam.ConnectToPort = 4006;            
            WebCam.ConnectToRemoteHost = true;
            WebCam.SelectedImageSource = WebcamVideoControl.VideoImageSource.RemoteServer;
        }
    }
}
